<template>
  <div class="treatment-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>治疗记录</span>
          <div class="header-actions">
            
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-right: 10px;"
            />
            <el-button type="primary" @click="searchTreatments">搜索</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="treatmentList" v-loading="loading" stripe>
        <el-table-column prop="id" label="治疗ID" width="180" />
        <el-table-column prop="user_id" label="用户" width="120" />
        <el-table-column prop="device_id" label="设备ID" width="180" />
        <el-table-column prop="treatment_mode" label="治疗模式" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
          <template #default="{ row }">
            {{ row.end_time ? formatDate(row.end_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="持续时间" width="120">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="viewTreatmentDetail(row.id)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTreatmentList } from '@/api/treatment'
import { formatDate, formatDuration } from '@/utils/format'

interface Treatment {
  id: string
  user_nickname: string
  device_id: string
  mode: string
  status: 'ongoing' | 'completed' | 'cancelled'
  start_time: string
  end_time: string | null
  duration: number
}

const router = useRouter()
const loading = ref(false)
const treatmentList = ref<Treatment[]>([])
const dateRange = ref<[Date, Date] | null>(null)

const searchForm = reactive({
  keyword: '',
  status: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loadTreatmentList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status,
      startTime: dateRange.value?.[0] ? dateRange.value[0].toISOString() : undefined,
      endTime: dateRange.value?.[1] ? dateRange.value[1].toISOString() : undefined
    }
    const response: any = await getTreatmentList(params)
    treatmentList.value = response.records
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取治疗记录失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const searchTreatments = () => {
  pagination.currentPage = 1
  loadTreatmentList()
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'interrupted': return 'primary'
    case 'completed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'interrupted': return '已中断'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return status
  }
}

const viewTreatmentDetail = (treatmentId: string) => {
  router.push(`/treatments/detail/${treatmentId}`)
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadTreatmentList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadTreatmentList()
}

onMounted(() => {
  loadTreatmentList()
})
</script>

<style scoped lang="scss">
.treatment-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>